package com.young.pattern.prototypePattern;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 具体原型类
 */
@Data
@Slf4j
@EqualsAndHashCode
public class WeeklyLog implements Serializable {

    private String name;
    private String content;
    private String date;
    private Attachment attachment;

    public WeeklyLog clone(){
        Object obj = null;
        try {
            obj = super.clone();
        } catch (CloneNotSupportedException e) {
            log.error("克隆异常:{}",e.getMessage());
            e.printStackTrace();
        }
        return (WeeklyLog) obj;
    }

    //  使用序列化技术实现深克隆
    public WeeklyLog deepClone(){

        try {
            //  读取当前流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //  写入新的流
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (WeeklyLog) ois.readObject();
        } catch (Exception e) {
            log.error("克隆异常:{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}
